let request = require('operation.js')
let bxt = require('../utils/bxt.js')

module.exports.createReceipt = createReceipt

/**
 * params {}
 * 根据不同的情况传入不同数据
 */
function createReceipt(source,params) {
  let that = source

  if (that.setButtonLoading) {
    that.setButtonLoading(true)
  }
  
  return new Promise((resolve, reject) => {
    request.startRequest('POST', '/receipts', params, true)
      .then(res => {
        if (that.setButtonLoading) {
          that.setButtonLoading(false)
        }
        let data = res.data
        if (request.SUCCESSED == data.status) {
          wx.showToast({
            title: '签收成功',
            icon: "success"
          })
          // 更新内存中保留的签收数据,为了让通知详情、签收学生选择、通知列表界面刷新界面
          let receiptObject = data.object
          let receiptStatus = getApp().globalData.param.notice.receiptStatus[0].currentStatus.split('/');
          let receipted = parseInt(receiptStatus[0]) + 1, noreceipted = receiptStatus[1]
          getApp().globalData.param.notice.receiptStatus[0].currentStatus = receipted + '/' + noreceipted;
          if (null == getApp().globalData.param.notice.myReceipts) {  // 从卡片绑定关系后，进行签收后，服务器回的是null
              getApp().globalData.param.notice.myReceipts = []
          }
          getApp().globalData.param.notice.myReceipts.push(data.object)
          getApp().notificationCenter.post(bxt.RECEIPT_SUCCESSED_MESSAGE, { receiptObject })

          resolve(receiptObject)
        }else {
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
        }
      })
      .catch(e => {
        if (that.setButtonLoading) {
          that.setButtonLoading(false)
        }
        wx.showToast({
          title: e,
          icon: 'none'          
        })
      })
  })
    
}